package com.lu.spzx.service.handler;

import com.alibaba.fastjson.JSON;
import com.lu.spzx.model.entity.user.UserInfo;
import com.lu.spzx.service.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果 token 不为空,那么此时验证 token 的合法性
        String userInfoJSON = this.redisTemplate.opsForValue().get("user:login:" + request.getHeader("token"));
        // 转换类型
        UserInfo userInfo = JSON.parseObject(userInfoJSON, UserInfo.class);
        AuthContextUtil.set(userInfo);
        return true;

    }

    /**
     * 在当前请求响应之前,清楚信息.
     * 否则线程返回到线程池,有可能不被清除,在下一个请求来时,会保留上一个请求用户的信息,造成安全问题
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }

}